package lego.jbv;

import java.util.ArrayList;

import lego.animal.IAnimal;
import lego.animal.Lion;
import lego.animal.Wolf;
import lejos.nxt.Button;
import lejos.nxt.ButtonListener;
import lejos.nxt.LCD;
import lejos.nxt.MotorPort;
import lejos.nxt.SensorPort;
import lejos.nxt.addon.RCXMotor;
import lejos.util.Delay;

public class Predator {
	private static BTController btc;
	private static BumperController bmc;
	private static ArrayList<String> messages;
	private static IAnimal animal;
	private static Driver driver;
	private static SoundController soundController;

	public static void main(String[] args) {
		initiate();
		
		soundController = new SoundController();
		soundController.start();
		
		messages = new ArrayList<>();
		
		ArrayList<IAnimal> animals = new ArrayList<>();
		animals.add(new Lion());
		animals.add(new Wolf());
		
		animal = IAnimal.selectAnimal(animals);
		
		Display.init(animal);
		Display.setStatus("Warming up");
		
		//Start engine
		driver = new Driver();
		driver.start();
		
		//Start BlueTooth thread
		btc = new BTController(messages, animal, driver, soundController);
		btc.start();
		
		//Start hit detection
		bmc = new BumperController(messages, SensorPort.S4, SensorPort.S1);
		bmc.start();

		//Start exhaustion
		Exhaustion exhaustion = new Exhaustion(driver);
		exhaustion.start();
		
		//Start hunger
		Hunger hunger = new Hunger();
		hunger.start();
		
		while(hunger.isAlive())
		{
			Thread.yield();
		}
		
		driver.exit();
		bmc.stop();
		exhaustion.stop();
		hunger.stop();
		
		Delay.msDelay(5000);
		System.exit(0);
	}
	
	private static void initiate()
	{
		Button.ESCAPE.addButtonListener(new ButtonListener() {
			
			@Override
			public void buttonReleased(Button b) {
				exit();			
			}
			
			@Override
			public void buttonPressed(Button b) {
				// TODO Auto-generated method stub
				
			}
		});

		turnOnLight(MotorPort.B);
	}
	
	private static void exit()
	{
		driver.exit();
		btc.stop();
		bmc.stop();
		turnOffLight(MotorPort.B);
		Display.setStatus("You died");
		Delay.msDelay(3000);
		System.exit(0);
	}
	
	private static void turnOnLight(MotorPort port)
	{
		RCXMotor rx = new RCXMotor(port);
		rx.setPower(100);
	}
	
	private static void turnOffLight(MotorPort port)
	{
		RCXMotor rx = new RCXMotor(port);
		rx.setPower(0);
	}

}
